# coding=utf-8
import os,sys
import hashlib
import time
import json
import requests
from aip import AipOcr


class TmpObj():
    def __init__(self):
        self.value = None


class Rsp():
    def __init__(self):
        self.ret_code = -1
        self.cust_val = 0.0
        self.err_msg = "succ"
        self.pred_rsp = TmpObj()

    def ParseJsonRsp(self, rsp_data):
        if rsp_data is None:
            self.err_msg = "http request failed, get rsp Nil data"
        jrsp = json.loads(rsp_data)
        self.ret_code = int(jrsp["RetCode"])
        self.err_msg = jrsp["ErrMsg"]
        self.request_id = jrsp["RequestId"]
        if self.ret_code == 0:
            rslt_data = jrsp["RspData"]
            if rslt_data is not None and rslt_data != "":
                jrsp_ext = json.loads( rslt_data)
                if "cust_val" in jrsp_ext:
                    data = jrsp_ext["cust_val"]
                    self.cust_val = float(data)
                if "result" in jrsp_ext:
                    data = jrsp_ext["result"]
                    self.pred_rsp.value = data


def CalcSign(pd_id, passwd, timestamp):
    md5 = hashlib.md5()
    md5.update((timestamp + passwd).encode())
    csign = md5.hexdigest()
    md5 = hashlib.md5()
    md5.update((pd_id + timestamp + csign).encode())
    csign = md5.hexdigest()
    return csign


def CalcCardSign(cardid, cardkey, timestamp, passwd):
    md5 = hashlib.md5()
    md5.update(passwd + timestamp + cardid + cardkey)
    return md5.hexdigest()


def HttpRequest(url, body_data, img_data=""):
    rsp = Rsp()
    post_data = body_data
    files = {'img_data':('img_data',img_data)}
    header = {'User-Agent': 'Mozilla/5.0',}
    rsp_data = requests.post(url, post_data,files=files ,headers=header)
    rsp.ParseJsonRsp(rsp_data.text)
    return rsp
	

class FateadmApi():
    def __init__(self, app_id, app_key, pd_id, pd_key):
        self.app_id = app_id
        if app_id is None:
            self.app_id = ""
        self.app_key = app_key
        self.pd_id = pd_id
        self.pd_key = pd_key
        self.host = "http://pred.fateadm.com"

    def SetHost(self, url):
        self.host = url

    def QueryBalc(self):
        tm = str(int(time.time()))
        sign = CalcSign(self.pd_id, self.pd_key, tm)
        param = {"user_id": self.pd_id, "timestamp": tm, "sign": sign}
        url = self.host + "/api/custval"
        rsp = HttpRequest(url, param)
        return rsp

    def QueryTTS(self, pred_type):
        tm = str( int(time.time()))
        sign = CalcSign( self.pd_id, self.pd_key, tm)
        param = {
                "user_id": self.pd_id,
                "timestamp":tm,
                "sign":sign,
                "predict_type":pred_type,
                }
        if self.app_id != "":
            asign = CalcSign(self.app_id, self.app_key, tm)
            param["appid"] = self.app_id
            param["asign"] = asign
        url = self.host + "/api/qcrtt"
        rsp = HttpRequest(url, param)
        return rsp

    def Predict(self, pred_type, img_data, head_info = ""):
        tm = str( int(time.time()))
        sign = CalcSign( self.pd_id, self.pd_key, tm)
        param = {
                "user_id": self.pd_id,
                "timestamp": tm,
                "sign": sign,
                "predict_type": pred_type,
                "up_type": "mt"
                }
        if head_info is not None or head_info != "":
            param["head_info"] = head_info
        if self.app_id != "":
            asign = CalcSign(self.app_id, self.app_key, tm)
            param["appid"] = self.app_id
            param["asign"] = asign
        url = self.host + "/api/capreg"
        files = img_data
        rsp = HttpRequest(url, param, files)
        return rsp

    def PredictFromFile( self, pred_type, file_name, head_info = ""):
        with open(file_name, "rb") as f:
            data = f.read()
        return self.Predict(pred_type,data,head_info=head_info)

    def Justice(self, request_id):
        if request_id == "":
            return
        tm = str( int(time.time()))
        sign = CalcSign( self.pd_id, self.pd_key, tm)
        param = {
                "user_id": self.pd_id,
                "timestamp":tm,
                "sign":sign,
                "request_id":request_id
                }
        url = self.host + "/api/capjust"
        rsp = HttpRequest(url, param)

        return rsp

    def Charge(self, cardid, cardkey):
        tm = str( int(time.time()))
        sign = CalcSign( self.pd_id, self.pd_key, tm)
        csign = CalcCardSign(cardid, cardkey, tm, self.pd_key)
        param = {
                "user_id": self.pd_id,
                "timestamp":tm,
                "sign":sign,
                'cardid':cardid,
                'csign':csign
                }
        url = self.host + "/api/charge"
        rsp = HttpRequest(url, param)
        return rsp

    def ExtendCharge(self, cardid, cardkey):
        return self.Charge(cardid,cardkey).ret_code
		
    def JusticeExtend(self, request_id):
        return self.Justice(request_id).ret_code

    def QueryBalcExtend(self):
        rsp = self.QueryBalc()
        return rsp.cust_val
    def PredictFromFileExtend( self, pred_type, file_name, head_info = ""):
        rsp = self.PredictFromFile(pred_type,file_name,head_info)
        return rsp.pred_rsp.value

    def PredictExtend(self,pred_type, img_data, head_info = ""):
        rsp = self.Predict(pred_type,img_data,head_info)
        return rsp.pred_rsp.value


def TestFunc(filePath):
    pd_id = "121606"     
    pd_key = "atG6dj5M7ywsuWcZoPLTfmwwuhtuQhnL"
    app_id = "321606"     
    app_key = "zxmXQfS8OgNttaDGyUJ3cfmC75SapC9h"
    pred_type = "30400"
    api = FateadmApi(app_id, app_key, pd_id, pd_key)
    balance = api.QueryBalcExtend()
    result = api.PredictFromFileExtend(pred_type,filePath)   # 直接返回识别结果
    # rsp             = api.PredictFromFile(pred_type, filePath)  # 返回详细识别结果
    # 如果不是通过文件识别，则调用Predict接口：
    # result 			= api.PredictExtend(pred_type,data)   	# 直接返回识别结果
    # rsp               = api.Predict(pred_type,data)			# 返回详细的识别结果
    return result


def baiduapi(filePath):
    APP_ID = '24062576'
    API_KEY = 'AhySNckGBXG3dbje5s8rlxlD'
    SECRET_KEY = 'GQvEgUtvuG5UjhvhICUz8zI2h7QNIPva'
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    with open(filePath, 'rb') as fp:
        try:
            ret = client.basicGeneral(fp.read())
            return ret['words_result'][0]['words']
        except:
            return None
	

if __name__ == "__main__":
    import sys
    TestFunc(sys.argv[1])


